<?php
/**
 * @param $source 背景图
 * @param $text1 文本1
 * @param $text2  文本2
 * @param $text3  文本3
 * @param string $img1 待合成图片1
 * @param string $font  字体
 * @return string
 */
function generateImg($source, $text1, $text2, $text3,$img1='', $font = './msyhbd.ttf')
{
    $date = '' . date('Ymd') . '/';
    $img = $date . md5($source . $text1 . $text2 . $text3) . '.jpg';
    if (file_exists('./' . $img)) {
        return $img;
    }

    $main = imagecreatefromjpeg($source);

    $width = imagesx($main);
    $height = imagesy($main);

    $target = imagecreatetruecolor($width, $height);

    $white = imagecolorallocate($target, 255, 255, 255);
    imagefill($target, 0, 0, $white);

    imagecopyresampled($target, $main, 0, 0, 0, 0, $width, $height, $width, $height);

    $fontSize = 20;//磅值字体
    $fontColor = imagecolorallocate($target, 9, 9, 9);//字的RGB颜色
    $fontColor2 = imagecolorallocate($target, 255, 9, 9);//字的RGB颜色
    imagettftext($target, $fontSize, 0, ceil(50), 100, $fontColor, $font, $text1);

    $fontBox = imagettfbbox($fontSize, 0, $font, $text2);
    imagettftext($target, $fontSize, 0, ceil(($width - $fontBox[2]) / 2), 200, $fontColor, $font, $text2);

    $fontBox = imagettfbbox($fontSize, 0, $font, $text3);
    imagettftext($target, $fontSize, 0, ceil(($width - $fontBox[2]) / 2), 560, $fontColor2, $font, $text3);


    //bof of 合成图片
    $child1 = imagecreatefromjpeg($img1);
    imagecopymerge($target, $child1, ceil(($width - $fontBox[2]) / 2), 250, 0, 0, imagesx($child1), imagesy($child1), 100);
    //eof of 合成图片

    @mkdir('./' . $date);
    imagejpeg($target, './' . $img, 95);

    imagedestroy($main);
    imagedestroy($target);
    imagedestroy($child1);
    return $img;
}

//http://my.oschina.net/cart/
$img = generateImg('./back.jpg',
    '《php实现文字嵌入图片和图片合成》',
    '玩转这样的功能代码，你还能体会到作为一只程序猿独有的乐趣。',
    '扫一扫关注公众号',
    './erweima.jpg'
);
exit ('图片生成成功,图片存放目录： ' . $img);
//输出:图片生成成功,图片存放目录： 20180626/5b738de39152b4aa00aea5d3dba1e9b1.jpg